<?php
namespace app\wechat\controller;
use \think\Db;
use think\Log;
class Cooperation extends Common  {

    public function __construct() {
        parent::__construct();
    }

   /**
     * 查询机构列表
     * @Author   sxh
     * @Email    xh.shi@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */
    public function institutions() {
        $list=Db::table('my_partners_due')->where(['dd_status'=>4])->order('partner_order desc')->paginate(10,$false);
        $page['lastPage']=$list->lastPage();
        $page['currentPage']=$list->currentPage();
        $page['total']=$list->total();
        $page['listRows']=$list->listRows();
        return $this->fetch("list",['list'=>$list,'page'=>$page]);
    } 
    
    /**
     * 展示机构详情
     * @Author   sxh
     * @Email    xh.shi@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */ 
    public function detail(){
        $request = request();
        $params = $request->param();
        $map['pd.dd_id']=intval($params['id']);
        $detail=Db::table("my_partners_due")->alias('pd')->join("my_partners_desc mpd","mpd.dd_id=pd.dd_id","LEFT")->where($map)->find();
        return $this->fetch("detail",['vo'=>$detail]);
    }

    public function servicePartner()
    {
        $params = request()->param();
        return $this->fetch("/agreement/servicePartner",$params);
    }

    /**
     * Desc: 框架合同协议（申请合同时）
     * User: liuning
     * Date: 2018/12/22 16:15
     * Return: array
     * Update:
     */
    public function serviceContract()
    {
        $params = request()->param();

        //获取银行卡类型是否存在结算账户(个人),存在即需要上传手持身份证、结算银行卡(个人)、手持银行卡证件
        $where['partner_id'] = $params['partner_id'];//机构id
        $where['partner_account_status'] = 0;//帐号状态【0启用，1停用】
        $where['partner_account_type'] = 3;//帐号类型【0个人银行卡，1对公银行卡（基础账户），2工蚂付结算账户(企业)，3工蚂付结算账户(个人)，4持牌金融结算账户(企业)】
        $result=Db::table("my_partners_bank")->where($where)->select();
        if(!empty($result)){
            $params['is_personal_bank_card'] = 1;
        }

        return $this->fetch("/agreement/serviceContract",$params);
    }

    /**
     * Desc: 蚂蚁账单管理合作协议
     * User: liuning
     * Date: 2018/12/24 11:27
     * Return: array
     * Update: 
     */
    public function serviceContractMY()
    {
        $params = request()->param();
        return $this->fetch("/agreement/serviceContractMY",$params);
    }

    /**
     * Desc: 持牌金融机构学费账单管理协议
     * User: liuning
     * Date: 2018/12/24 11:27
     * Return: array
     * Update: 
     */
    public function serviceContractFee()
    {
        $params = request()->param();
        $where['partner_id'] = $params['partner_id'];//机构id
        //获取蚂蚁账单课程列表
        $result = $this->getWS('credit', 'Product@productList', $where);
        //目前持牌金融机构账单（信用卡）跟蚂蚁账单一致
        if($result['status'] == 2000){
            $params['p_service_price'] = $result['result'][0]['p_service_price'];//每期固定金额服务费
            $params['p_partner_service'] = $result['result'][0]['p_partner_service'];//商户或用户支付每期服务费（0用户 1机构）
        }
        return $this->fetch("/agreement/serviceContractFee",$params);
    }

    /**
     * Desc: 课程协议
     * User: liuning
     * Date: 2018/12/24 11:29
     * Return: array
     * Update:
     */
    public function serviceContractPro()
    {
        $params = request()->param();
//        $params['partner_id'] = 262;
        $where['partner_id'] = $params['partner_id'];//机构id
//        $where['b.p_status'] = 1;//上线课程
//        $where['b.p_return_type'] = array('in','2,4');// 1等额本息，2等本等息, 3等额本金，4x+y模式）
//        $result=Db::table("my_product")->alias('b')->join("my_partners p","p.partner_id=b.partner_id","LEFT")->where($where)->select();

        //获取蚂蚁账单课程列表
        $result = $this->getWS('credit', 'Product@productList', $where);
        $p_return_type2 = [];
        $p_return_type4 = [];
        if($result['status'] == 2000){
            if(!empty($result['result'])){
                foreach ($result['result'] as $key => $value) {
                    if($value['p_return_type'] == 2){
                        //等本等息
                        $p_return_type2[$value['p_name']][] = $value;

                        //计算金额
                        if(!empty($p_return_type2[$value['p_name']])){
                            foreach($p_return_type2[$value['p_name']] as $k => $v){
                                $not_pay_amount = $v['p_set_amount'] - $v['p_first_payment'];//未付金额
                                $benjin_amount = round(($not_pay_amount/$v['p_period']),2);//每期本金交费
                                $service_price_total = round(($v['p_service_price'] * $v['p_period']),2);//总服务费

                                $p_return_type2[$value['p_name']][$k]['not_pay_amount'] = $not_pay_amount;
                                $p_return_type2[$value['p_name']][$k]['benjin_amount'] = $benjin_amount;
                                $p_return_type2[$value['p_name']][$k]['service_price_total'] = $service_price_total;
                            }
                        }

                    }else if($value['p_return_type'] == 4){
                        //x+y模式
                        $p_return_type4[$value['p_name']][] = $value;

                        //计算金额
                        if(!empty($p_return_type4[$value['p_name']])){
                            foreach($p_return_type4[$value['p_name']] as $k => $v){
                                $not_pay_amount =  $v['p_set_amount'] - $v['p_first_payment'];//未付金额
                                $benjin_amount = round($not_pay_amount/$v['p_y_month'],2);//每期本金交费
                                $service_price_total = round(($v['p_service_price'] * $v['p_period']),2);//总服务费

                                $p_return_type4[$value['p_name']][$k]['not_pay_amount'] = $not_pay_amount;
                                $p_return_type4[$value['p_name']][$k]['benjin_amount'] = $benjin_amount;
                                $p_return_type4[$value['p_name']][$k]['service_price_total'] = $service_price_total;
                            }
                        }
                    }
                }
            }
        }



        if(!empty($p_return_type2)){
            $params['p_return_type2'] = $p_return_type2;
            $params['is_p_return_type2'] = 2;//等本等息方案
        }
        if(!empty($p_return_type4)){
            $params['p_return_type4'] = $p_return_type4;
            $params['is_p_return_type4'] = 4;//x+y方案
        }
        $params['p_service_price'] = $result['result'][0]['p_service_price'];//每期固定金额服务费
        $params['p_partner_service'] = $result['result'][0]['p_partner_service'];//商户或用户支付每期服务费（0用户 1机构）

        return $this->fetch("/agreement/serviceContractPro",$params);
    }

    /**
     * Desc: 工蚂付特约商户服务协议
     * User: liuning
     * Date: 2018/12/24 11:29
     * Return: array
     * Update:
     */
    public function serviceContractGmf()
    {
        $params = request()->param();
        return $this->fetch("/agreement/serviceContractGmf",$params);
    }

    /**
     * Desc: 学员协议付认证银行卡，（协议付-获取宝付-协议付认证ID）
     * User: liuning
     * Date: 2019/2/22 10:11
     * Return: array
     * Update:
     */
    public function authentication()
    {
        $params = request()->param();
        if(!session('uid')){
            session('protocol_no',1);
            return view('pay/paylogin');
        }
        //查询用户姓名、身份证号、银行卡号、预留手机号
        $userBank = $this->getWS('ucenter', 'bank@userBank', ['u_code'=>$this->uid]);
        if($userBank['status'] == '2000'){
            $params['real_name']  = $userBank['result']['real_name'];//姓名
            $params['ident_no']   = $userBank['result']['ident_no'];//身份证号
            if(!empty($userBank['result']['banks'])){
                $params['ub_card_no']  = $userBank['result']['banks'][0]['ub_card_no'];//银行卡号
                $params['ub_phone']   = $userBank['result']['banks'][0]['ub_phone'];//预留手机号
                $params['is_userBank']  = 1;//获取用户银行卡信息成功
            }else{
                $params['is_userBank']  = 2;//获取用户银行卡信息失败
            }
        }
        return view("agreement/authentication",$params);
    }


    /**
     * Desc: 绑定随机发给机构的桌牌二维码
     *       channel服务二维码生成地址:/binDingcode?qr_code=QR985731706
     *       扫码绑定进入页面：IcbcPay/productSelect
     * User: liuning
     * Date: 2019/3/18 10:32
     * Return: array
     * Update:
     */
    public function bindPartnerQrCode($params)
    {
        $params       = $this->xaddslashes($params);
        // 参数校验
        if(empty($params['partner_no']) || !is_numeric($params['partner_no']) || empty($params['contact_phone']) || !is_numeric($params['contact_phone']) ||
            empty($params['qr_code']) || empty($params['token_id']) || $params['token_id'] != substr(md5('MYBLJHZF'), 0, 16)){

            return $this->parse_data(['code'=>'5000', 'msg'=>'参数传输错误']);
        }

        $qr_code = base64_decode($params['qr_code']);

        //查询是否绑定
        $qRcodeAct = $this->getWS('credit', 'Aggregate@getQRcodeAct', ['qr_code'=>$qr_code]);
        if($qRcodeAct['status'] != '2000'){
            return $this->parse_data(['code'=>'5000', 'msg'=>'查询机构二维码失败']);
        }

        if($qRcodeAct['result']['qr_status'] == 1){
            return $this->parse_data(['code'=>'5000', 'msg'=>'该二维码已有机构绑定']);
        }

        $paramsPartners = [
            'partner_no' => $params['partner_no'],
            'contact_phone' => $params['contact_phone'],
        ];

        //查询机构号是否存在，机构联系人手机号是否正确
        $partner = $this->getWS('credit', 'Partners@getPartnerInfo', $paramsPartners);
        if($partner['status'] == '2000'){
            $partner_id = $partner['result'];
        }else{
            return $this->parse_data(['code'=>'5000', 'msg'=>$partner['msg']]);
        }

        $updateData = [
            'qr_code'=>$qr_code,
            'where'=>[
                'partner_id'=>$partner_id,
                'partner_no'=>$params['partner_no'],
                'qr_status'=>1,
                'update_time'=>date('Y-m-d H:i:s',time()),
            ],
        ];


        $partner = $this->getWS('credit', 'Partners@bindPartnerQrCode', $updateData);

        //返回日志
        $logParams = ['contact_phone'=>$params['contact_phone'],'updateData'=>$partner];
        Log::write($logParams, '绑定二维码返回结果', true, 'bindPartnerQrCode/');

        if($partner['status'] == '5000'){
            return $this->parse_data(['code'=>'5000', 'msg'=>'绑定失败']);
        }

        $jump_url = config('wechat.'. APP_ENV)['weburl']."/productSelect?qr_code=".$params['qr_code'].'&token_id='. $params['token_id'];
        return $this->parse_data(['code'=>'2000', 'msg'=>'绑定成功','data' => ['jumpUrl' => $jump_url]]);
    }
}